import { useRef } from 'react';
import { useDrag, useDrop } from 'react-dnd';

export default ({ index, moveRow, className, style, ...restProps }) => {
  const type = 'DragbleBodyRow';
  const menuRef = useRef();

  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: type,
    collect: (monitor) => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? 'drop-over-downward' : 'drop-over-upward',
      };
    },
    drop: (item) => {
      moveRow(item.index, index);
    },
  });

  const [, drag] = useDrag({
    item: { type, index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  drop(drag(menuRef));

  return <tr ref={menuRef} style={{ cursor: 'move', ...style }} {...restProps} />;
};
